/* socket 通信的服务端 */

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);

// 创建服务端 Socket 对象
const { Server } = require("socket.io");
const io = new Server(server);
// 监听端口，等待客户端的连接
// 当有客户端连接到服务器时，会触发事件处理程序
io.on('connection', (socket) => {
  // socket 参数代表的是连接到服务端的客户
  console.log('a user connected');
  // 向客户端发送欢迎消息
  socket.emit('clientReceive', '欢迎您加入聊天！');

  // 注册事件监听，接收客户端发送的消息
  socket.on('serverReceive', (msg) => {
    console.log('message: ' + msg);
    // 将接收到的消息转发给所有连接到服务器的客户端
    io.emit('clientReceive', msg)
  });

  // 当前客户端断开连接时触发
  socket.on('disconnect', () => {
    console.log('user disconnected');
  });
});

app.get('/', (req, res) => {
  // res.send('<h1>Hello world</h1>');
  res.sendFile(__dirname + '/index.html')
});

server.listen(3000, () => {
  console.log('listening on *:3000');
});
